package com.project.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;


@Configuration
@ComponentScan({"com.project.service","com.project.mapper"})
@EnableTransactionManagement
@MapperScan("com.project.mapper")
public class MybatisConfig {
    @Bean
    public DataSource getData(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:12345/dbTest?characterEncoding=utf-8&allowMultiQueries=true");
        dataSource.setUsername("root");
        dataSource.setPassword("lovo");
        dataSource.setMaxActive(100);
        dataSource.setMinIdle(20);
        dataSource.setMaxWait(1000);

        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean getFactory(){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setConfigLocation(new ClassPathResource("mybatis.cfg.xml"));
        factoryBean.setDataSource(this.getData());

        return factoryBean;
    }

    @Bean
    public TransactionManager getTrans(){
        DataSourceTransactionManager trans = new DataSourceTransactionManager();
        trans.setDataSource(this.getData());

        return trans;
    }

}
